package com.codingfuture.erp_system.service.impl;

import com.codingfuture.erp_system.dto.RoleMenuDto;
import com.codingfuture.erp_system.entity.Role;
import com.codingfuture.erp_system.entity.RoleMenu;
import com.codingfuture.erp_system.mapper.RoleAuthorityMapper;
import com.codingfuture.erp_system.service.RoleAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleAuthorityServiceImpl implements RoleAuthorityService {

    @Autowired
    private RoleAuthorityMapper roleAuthorityMapper;

    @Override
    public List<Role> findByAll() {
        return roleAuthorityMapper.findByAll();
    }

    @Override
    public List<RoleMenu> findById(int id) {
        return roleAuthorityMapper.findById(id);
    }

    @Override
    public List<RoleMenuDto> findByMenu() {
        return roleAuthorityMapper.findByMenu();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(Integer roleId, String menuIds) {
        List<RoleMenu> roleMenuList = roleAuthorityMapper.findId(roleId);
        if (menuIds.length() != 0) {
            String[] split = menuIds.split(",");
            List<String> stringList = roleAuthorityMapper.findMenu(split);
            if (roleMenuList.size() != 0) {
                int row = roleAuthorityMapper.deleteById(roleId);
                if (row != 0) {
                    int rows = roleAuthorityMapper.addById(roleId, stringList);
                    int line = roleAuthorityMapper.addId(roleId, split);
                    if (rows != 0 && line != 0) {
                        return true;
                    }
                }
                return false;
            } else {
                int rows = roleAuthorityMapper.addById(roleId, stringList);
                int line = roleAuthorityMapper.addId(roleId, split);
                if (rows != 0 && line != 0) {
                    return true;
                }
            }
            return false;
        } else {
            return roleAuthorityMapper.deleteById(roleId) != 0;
        }

    }
}
